package com.my.wangpan;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.my.wangpan.net.CloudEngine;
import com.my.wangpan.net.IDataCallBack;
import com.my.wangpan.util.ExceptionHandler;
import com.my.wangpan.util.Utils;
import com.vdisk.android.VDiskAuthSession;
import com.vdisk.net.RESTUtility;
import com.vdisk.net.VDiskAPI;
import com.vdisk.net.VDiskAPI.Entry;
import com.vdisk.net.session.AppKeyPair;
import com.vdisk.net.session.Session;
import com.my.*;

import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2016/10/26.
 */
public class MainActivity extends Activity implements IDataCallBack {

    private PullToRefreshListView pullToRefreshListView;
    VDiskAPI<VDiskAuthSession> mApi;
    private List<Entry> mEntry;
    private String mPath="/";
//    private Handler mHandler = new Handler(){
//        @Override
//        public void handleMessage(Message msg) {
//            //2.加载完成刷新了
//            pullToRefreshListView.onRefreshComplete();
//            mEntry = (List<Entry>) msg.obj;
//            //刷新UI
//            adapter.notifyDataSetChanged();
//        }
//    };
    private FileListAdapter adapter;
    private ListView mListView;
    private long mPreTime = System.currentTimeMillis();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
        initView();
        initData(mPath);
        initListener();
//        initActionBar();
    }

//    private void initActionBar() {
//        android.app.ActionBar actionBar = getActionBar();
//        actionBar.setDisplayShowHomeEnabled(false);
//        actionBar.setTitle("黑马网盘");
//    }

    private void init() {
        AppKeyPair appKeyPair = new AppKeyPair(LoginActivity.CONSUMER_KEY,LoginActivity.CONSUMER_SECRET);
        /**
         * 正式的环境 VDISK("box")
         * 测试的环境 APP_FOLDER("sandbox")-->支付的（1分钱）
         */
        VDiskAuthSession session = VDiskAuthSession.getInstance(this, appKeyPair, Session.AccessType.VDISK);

        mApi = new VDiskAPI<VDiskAuthSession>(session);
    }

    private void initView() {

        pullToRefreshListView = (PullToRefreshListView) findViewById(R.id.listView);
        mListView = pullToRefreshListView.getRefreshableView();
    }

    private void initData(String path) {
        //加载数据的时候应该显示下载刷新中的视图
        pullToRefreshListView.setRefreshing();//1.显示正在加载的效果
        //加载完成关闭加载
        //拉取更目录文件信息
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                Entry metadata = null;
//                try {
//                    metadata = mApi.metadata("/", null, true, false);
//                    List<Entry> contents = metadata.contents;
//                    Message msg = Message.obtain();
//                    msg.obj = contents;
//                    //需要handler发送消息到主线程
//                    mHandler.sendMessage(msg);
//                } catch (VDiskException e) {
//                    e.printStackTrace();
//                }
//            }
//        }).start();
        CloudEngine.getInstance(this).getFileList(this,path,CloudEngine.REQ_FILE_LIST);
        //设置adapter
        adapter = new FileListAdapter();
        mListView.setAdapter(adapter);
    }

    private void initListener() {
        pullToRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //重新请求网络加载数据
                initData(mPath);
            }
        });

        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                i = i - mListView.getHeaderViewsCount();//处理添加头之后的position问题
                Entry entry = mEntry.get(i);
                //点击进入子目录
                if(entry.isDir){
                    enterFolder(entry);
                }
//                CloudEngine.getInstance(MainActivity.this).deleteFile(MainActivity.this,entry.path+"asdasd",CloudEngine.REQ_FILE_DELETE);
            }


        });
    }

    /**进入子目录*/
    private void enterFolder(Entry entry) {
        mPath = entry.path;
        initData(mPath);
    }

    /*
    统一处理访问的结果
    1.拉取文件信息列表的时候-->
    2.删除文件的时候
     */
    @Override
    public void handleServerData(int reqCode, int errCode, Object data) {
        if (errCode != 0){
            ExceptionHandler.toastErrMessage(MainActivity.this,errCode);
            return;
        }
        switch (reqCode){
            case CloudEngine.REQ_FILE_LIST:
                pullToRefreshListView.onRefreshComplete();
                mEntry = (List<Entry>) data;
                //刷新UI
                adapter.notifyDataSetChanged();
                break;
            case CloudEngine.REQ_FILE_DELETE:
                Entry   deleteEntry = (Entry) data;
                Toast.makeText(getApplicationContext(),"删除"+deleteEntry.fileName(),Toast.LENGTH_SHORT);
                break;
        }

    }

    private class FileListAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            if(mEntry != null ){
                return mEntry.size();
            }
            return 0;
        }

        @Override
        public Object getItem(int i) {
            if(mEntry != null ){
                return mEntry.get(i);
            }
            return null;
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View convertView, ViewGroup viewGroup) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = MainActivity.this.getLayoutInflater().inflate(R.layout.file_item, null);

                holder = new ViewHolder();
                holder.tvName = (TextView) convertView.findViewById(R.id.tv_name);
                holder.tvTime = (TextView) convertView.findViewById(R.id.tv_time);
                holder.tvSize = (TextView) convertView.findViewById(R.id.tv_size);
                holder.ivIcon = (ImageView) convertView.findViewById(R.id.iv_icon);
                holder.ivOption = (ImageView) convertView.findViewById(R.id.iv_option);
                holder.cbCheck = (CheckBox) convertView.findViewById(R.id.cb_checkbox);

                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            //赋值操作
            Entry entry = mEntry.get(i);
            holder.tvSize.setText(entry.size);
            holder.tvName.setText(entry.fileName());
            Date parseDate = RESTUtility.parseDate(entry.modified);
            holder.tvTime.setText(Utils.getFormateTime(parseDate));
            if(entry.isDir){
                holder.ivIcon.setImageResource(R.drawable.directory_icon);
            }else{
                //根据文件类型做不同的展示
                Object[] mimeType = Utils.getMIMEType(entry.fileName());
                //mimeType[0]-->mimetype
                //mimeType[1]-->图片
                holder.ivIcon.setImageResource((Integer) mimeType[1]);
            }
            return convertView;
        }

        class ViewHolder {
            TextView	tvName;
            TextView	tvTime;
            TextView	tvSize;

            ImageView ivIcon;
            ImageView	ivOption;

            CheckBox cbCheck;
        }
    }

//
//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if(keyCode == KeyEvent.KEYCODE_BACK){
//            initData("");
//        }
//        return super.onKeyDown(keyCode, event);
//    }

    /***
     * /   /美女  /美女/终止
     */
    @Override
    public void onBackPressed() {
        if("/".equals(mPath)){
            if (System.currentTimeMillis() - mPreTime > 2000){
                Toast.makeText(getApplicationContext(),"再按一次弹出网盘",Toast.LENGTH_SHORT).show();
                mPreTime = System.currentTimeMillis();
                return;
            }
            finish();
        }else{
            int index = mPath.lastIndexOf("/");
            mPath = mPath.substring(0,index);//  /美女/终止  得到的为  /美女/，   /美女  得到的为  “”   /  得到的为  “”
            if("".equals(mPath)){
                mPath = "/";
            }
            initData(mPath);
        }


//        super.onBackPressed();--->会调用finish()
    }
}
